package cn.signalpha.modules.pay.controller;

import cn.signalpha.common.annotation.FormRepeatCommitAnnotation;
import cn.signalpha.common.cache.ConfigCache;
import cn.signalpha.common.cache.ConfigKeys;
import cn.signalpha.common.constant.AppConstant;
import cn.signalpha.common.dto.ConfigDTO;
import cn.signalpha.core.boot.ctrl.BaseController;
import cn.signalpha.core.tool.api.R;
import cn.signalpha.core.tool.utils.StringPool;
import cn.signalpha.core.tool.utils.WebUtil;
import cn.signalpha.modules.pay.dto.PayDTO;
import cn.signalpha.modules.pay.dto.PayOrderDTO;
import cn.signalpha.modules.pay.enums.PayTypeEnum;
import cn.signalpha.modules.pay.provider.PayGranterBuilder;
import cn.signalpha.modules.pay.service.PayService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;
import java.util.Objects;


@RestController
@AllArgsConstructor
@RequestMapping(AppConstant.APPLICATION_PAY_NAME)
@Api(value = "支付", tags = "支付")
public class PayController extends BaseController {

    private final PayService payService;

	@PostMapping("/order")
	@FormRepeatCommitAnnotation
	@ApiOperation(value = "订单支付")
	public R order(@Valid @RequestBody PayOrderDTO payOrderDTO)  {
		if(Objects.equals(payOrderDTO.getPayType(), PayTypeEnum.WX_PAY.getType())){
			ConfigDTO.WxPayDTO config = ConfigCache.getObject(ConfigKeys.WX_PAY, ConfigDTO.WxPayDTO.class);
			if(config.getType().equals("v3")){
				payOrderDTO.setPayType(PayTypeEnum.WX_PAY_V3.getType());
			}
		}
		PayDTO payDTO = payService.orderPay(getUser().getUserId(), payOrderDTO.getOrderNo());
		payDTO.setIp(WebUtil.getIP());
		payDTO.setCode(payOrderDTO.getCode());
		payDTO.setAppId(payOrderDTO.getAppId());
		payDTO.setPayType(payOrderDTO.getPayType());
		payDTO.setPayClient(payOrderDTO.getPayClient());
		payDTO.setBankCardNo(payOrderDTO.getBankCardNo());
		payDTO.setNotifyUrl("/api/server-pay/notify/order");
		if(Double.parseDouble(payDTO.getPayMoney()) > 0){
			return R.data(PayGranterBuilder.getGranter(payOrderDTO.getPayType()).getPayVO(payDTO));
		}else{
			payService.orderPaySuccess(payDTO.getPayNo(), StringPool.EMPTY, payOrderDTO.getPayType());
			return R.data(StringPool.TRUE);
		}
	}

}
